package com.weilele.mvvm.utils.shortcut

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.pm.ShortcutInfo
import android.content.pm.ShortcutManager
import android.graphics.drawable.Drawable
import android.graphics.drawable.Icon
import android.os.Build
import androidx.annotation.DrawableRes
import androidx.annotation.RequiresApi
import androidx.core.content.getSystemService
import com.weilele.mvvm.app
import kotlin.math.min


private val shortcutManager by lazy { app.getSystemService<ShortcutManager>() }
private fun enableShortsCut(): Boolean {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1
}

data class ShortcutBean(
        val id: String,
        val jumpCls: Class<*>,
        val shortTitle: String,
        val longTitle: String,
        val disableTitle: String,
        @DrawableRes val icon: Int,
)

@RequiresApi(Build.VERSION_CODES.N_MR1)
fun setShortsCuts(shortcutInfo: MutableList<ShortcutBean>) {
    val results = initShortsCut(shortcutInfo)
    if (!results.isNullOrEmpty()) {
        shortcutManager?.dynamicShortcuts = results
    }
}

@RequiresApi(Build.VERSION_CODES.N_MR1)
fun removeShortcuts(shortcutInfo: MutableList<ShortcutBean>) {
    val results = initShortsCut(shortcutInfo)
    if (!results.isNullOrEmpty()) {
        shortcutManager?.removeDynamicShortcuts(shortcutInfo.map { it.id })
    }
}

@RequiresApi(Build.VERSION_CODES.N_MR1)
fun updateShortcuts(shortcutInfo: MutableList<ShortcutBean>) {
    val results = initShortsCut(shortcutInfo)
    if (!results.isNullOrEmpty()) {
        shortcutManager?.updateShortcuts(results)
    }
}

//设置动态shortcut
private fun initShortsCut(shortcutInfo: MutableList<ShortcutBean>): MutableList<ShortcutInfo>? {
    if (!enableShortsCut()) {
        return null
    }
    val manager = shortcutManager ?: return null
    val maxCount = manager.maxShortcutCountPerActivity
    val dynamicShortcuts: MutableList<ShortcutInfo> = mutableListOf()
    repeat(min(shortcutInfo.count(), maxCount)) {
        val bean = shortcutInfo[it]
        val intent = Intent(app, bean.jumpCls)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        intent.action = Intent.ACTION_VIEW
        val info = ShortcutInfo.Builder(app, bean.id) //设置id
                .setShortLabel(bean.shortTitle) //设置短标题
                .setLongLabel(bean.longTitle) //设置长标题
                .setDisabledMessage(bean.disableTitle) //设置长标题
                .setIcon(Icon.createWithResource(app, bean.icon)) //设置图标
                .setIntent(intent) //设置intent
                .build()
        dynamicShortcuts.add(info)
    }
    return dynamicShortcuts
}

/**
 * android 11 处理方案，参考此文章（https://blog.csdn.net/u010844304/article/details/111044338）
 * <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>
 */
data class AppInfoBean(val name: CharSequence,
                       val icon: Drawable)

//获取当前手机安装的应用列表
@SuppressLint("QueryPermissionsNeeded")
fun getAllInstallAppInfo(): List<AppInfoBean> {
    val pm = app.packageManager
    // 获取到所有安装了的应用程序的信息，包括那些卸载了的，但没有清除数据的应用程序
    val infos = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        pm.getInstalledPackages(PackageManager.MATCH_UNINSTALLED_PACKAGES)
    } else {
        pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES)
    }
    return infos.map {
        val appName = it.applicationInfo.loadLabel(pm)
        val icon = it.applicationInfo.loadIcon(pm)
        AppInfoBean(appName, icon)
    }
}

/**
 * 通过包名查询是否安装了app
 * packageName
 */
fun String?.isAppInstalled(): Boolean {
    this ?: return false
    val manager = app.packageManager
    return manager?.getLaunchIntentForPackage(this) != null
}
